package com.lanou.renrenxin.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.android.volley.toolbox.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by zouhui on 16/3/8.
 */
public class DiskCache implements ImageLoader.ImageCache{

    private  String cacheDir="";

    public DiskCache() {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//SD卡是否挂载
            File root = Environment.getExternalStorageDirectory();
            File ruiCache = new File(root.getAbsolutePath() + "/Renrenxin");
            if (!ruiCache.exists()) {
                ruiCache.mkdir();
            }
            cacheDir = ruiCache.getAbsolutePath();
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        if (url.contains(".jpg")||url.contains(".png")) {
            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
            return BitmapFactory.decodeFile(cacheDir + url);
        }else{
            return null;
        }
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (url.contains(".jpg")||url.contains(".png")) {
            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
            FileOutputStream fos = null;
            try {
                //初始化文件写入对象   添加路径
                fos = new FileOutputStream(cacheDir + "/" + url);
                //保存bitmap
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                if(null != fos){
                    try {
                        //这么写 怎么都会关
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
